package cn.virens.service.impl.sys.user;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.virens.CacheKeys;
import cn.virens.database.common.TransactionExecute;
import cn.virens.database.common.mapper.ExampleJoin;
import cn.virens.database.common.mapper.ExampleWrapper;
import cn.virens.database.mysql.mapper.sys.user.SysUserRoleRelationMapper;
import cn.virens.database.mysql.model.sys.user.SysUserRoleRelation;
import cn.virens.service.inter.sys.user.SysUserRoleRelationService;

/**
 * 用户表-角色-用户关系 - sys_user_role_relation
 *
 * @author Virens
 * @since  2019-10-25
 */
@Service
public class SysUserRoleRelationServiceImpl implements SysUserRoleRelationService {
	private @Autowired SysUserRoleRelationMapper mSysUserRoleRelationMapper;
	private @Autowired TransactionExecute mTransactionExecute;

	@Override
	@CacheEvict(cacheNames = CacheKeys.CACHE_MENUS, allEntries = true)
	public int putRoleList(String uuid, JSONArray array) {
		return mTransactionExecute.write((s) -> {
			ExampleWrapper example = ExampleWrapper.of(SysUserRoleRelation.class);
			example.and().andEqualTo("uuid", uuid);

			int answer = mSysUserRoleRelationMapper.deleteByExample(example);

			SysUserRoleRelation record = new SysUserRoleRelation();
			record.setUuid(uuid);

			for (int i = 0; i < array.size(); i++) {
				JSONObject obj = array.getJSONObject(i);

				record.setIdentity(obj.getString("identity"));
				record.setIsdefault(obj.getBoolean("isdefault"));

				answer += mSysUserRoleRelationMapper.insert(record);
			}

			return answer;
		});
	}

	@Override
	public List<Map<String, Object>> getRoleList(String uuid) {
		ExampleWrapper example = ExampleWrapper.of(SysUserRoleRelation.class);
		example.selectProperties("sys_user_role.name", "sys_user_role.identity", "sys_user_role_relation.isdefault");
		example.addJoinTable(ExampleJoin.left("sys_user_role", "sys_user_role.identity = sys_user_role_relation.identity"));
		example.and().andCondition("sys_user_role_relation.uuid = ", uuid);

		return mSysUserRoleRelationMapper.selectJoinMap(example);
	}
}
